package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;

import model.CategoryDataModel;
import model.CategoryModel;

import view.CategoryView;

/**
 * 07-01-2010
 * 
 * This class is the controller for saving all information from
 * CategoryView has this class as the eventlistener for the save button.
 * 
 * @author Martijn Scholten & Michel Rondhuis
 */
public class CategoryController implements ActionListener {

	private static CategoryView view;
	private static CategoryModel model;
	//private static CategoryController controller;

	/**
	 * Needs the model to initialize. Initiates the CategoryView singleton and
	 * adds is as an observer to the given model.
	 * 
	 * @param newModel
	 */
	public CategoryController(CategoryModel newModel) {
		if (newModel == null) {
			throw new NullPointerException();
		}
		model = newModel;
		view = CategoryView.getCategoryView(this);

		model.addObserver(view);
	}

	/**
	 * This opens the category view and sets its for a new category
	 */
	public void newCategory() {
		view.showNewOrEditCategoryOnBool(true);
	}

	/**
	 * This opens the categoryview and sets it for editting a category
	 */
	public void editCategory(int id) {
		CategoryDataModel category = model.getCategory(id);
		if (category == null) {
			throw new NullPointerException();
		} else {
			view.setCategoryId(id);
			view.setTitleField(category.getTitle());
			view.showNewOrEditCategoryOnBool(false);
		}
	}

	/**
	 * The Category calls this The ActionButton in the categoryview will trigger
	 * this ActionEvent.
	 */
	public void actionPerformed(ActionEvent e) {
		JButton button = (JButton) e.getSource();
		if (button.getText() == "Opslaan") {
			model.addCategory(view.getTitle());
			view.setTitleField("");


		} else if (button.getText() == "Wijzigen") {
			model.editCategory(view.getIdCategory(), view.getTitle());
			view.setTitleField("");
		}

	}

	/**
	 * Puts all the categories in the Vector.
	 */
	public Vector<CategoryDataModel> getCategoryList() {
		Vector<CategoryDataModel> list = new Vector<CategoryDataModel>();
		list = model.getAllCategories();	
		return list;	
	}
	/**
	 * Delete's the category
	 */
	public void deleteCategory(int id) {
		model.deleteCategory(id);
	}
	/**
	 * Sets the title in the view
	 */
	public void setTitle(String inputTekst) {
		view.setTitleField(inputTekst);
	}
	/**
	 * Sets the category ID
	 */
	public void setCategoryId(int id) {
		view.setCategoryId(id);
	}
}